# -*- coding: utf-8 -*-
# Author   : ZhangQing
# Time     : 2025-08-15
# File     : project_service.py
# Project  : codebuddy_craft
# Desc     : 项目服务

from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, update, delete
from typing import List, Optional, Dict, Any
import uuid
from datetime import datetime

from backend.models.project import Project
from backend.schemas.project import ProjectCreateRequest as ProjectCreate, ProjectUpdateRequest as ProjectUpdate
from backend.utils.logger import get_logger

logger = get_logger(__name__)

class ProjectService:
    """
    项目服务类
    
    处理项目相关的业务逻辑
    """
    
    @staticmethod
    async def create_project(db: AsyncSession, project_data: ProjectCreate, user_id: str) -> Project:
        """
        创建新项目
        """
        project = Project(
            id=str(uuid.uuid4()),
            name=project_data.name,
            description=project_data.description,
            user_id=user_id,
            created_at=datetime.utcnow(),
            updated_at=datetime.utcnow(),
            settings=project_data.settings or {},
            status="active"
        )
        
        db.add(project)
        await db.commit()
        await db.refresh(project)
        logger.info(f"Created project: {project.id} for user: {user_id}")
        return project
    
    @staticmethod
    async def get_project(db: AsyncSession, project_id: str) -> Optional[Project]:
        """
        获取项目详情
        """
        result = await db.execute(select(Project).where(Project.id == project_id))
        return result.scalar_one_or_none()
    
    @staticmethod
    async def get_user_projects(db: AsyncSession, user_id: str) -> List[Project]:
        """
        获取用户的所有项目
        """
        result = await db.execute(
            select(Project)
            .where(Project.user_id == user_id)
            .order_by(Project.updated_at.desc())
        )
        return result.scalars().all()
    
    @staticmethod
    async def update_project(db: AsyncSession, project_id: str, project_data: ProjectUpdate) -> Optional[Project]:
        """
        更新项目信息
        """
        update_data = project_data.dict(exclude_unset=True)
        update_data["updated_at"] = datetime.utcnow()
        
        await db.execute(
            update(Project)
            .where(Project.id == project_id)
            .values(**update_data)
        )
        await db.commit()
        
        return await ProjectService.get_project(db, project_id)
    
    @staticmethod
    async def delete_project(db: AsyncSession, project_id: str) -> bool:
        """
        删除项目
        """
        result = await db.execute(delete(Project).where(Project.id == project_id))
        await db.commit()
        return result.rowcount > 0
    
    @staticmethod
    async def update_project_settings(db: AsyncSession, project_id: str, settings: Dict[str, Any]) -> Optional[Project]:
        """
        更新项目设置
        """
        project = await ProjectService.get_project(db, project_id)
        if not project:
            return None
        
        # 合并设置
        updated_settings = {**project.settings, **settings}
        
        await db.execute(
            update(Project)
            .where(Project.id == project_id)
            .values(settings=updated_settings, updated_at=datetime.utcnow())
        )
        await db.commit()
        
        return await ProjectService.get_project(db, project_id)